<template>
  <div class="app-container">
    <!-- 排行榜标题 -->
    <el-card class="ranking-header">
      <div class="header-content">
        <h2>OJ排行榜</h2>
        <p>展示编程能力最强的用户</p>
      </div>
    </el-card>

    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-form-item label="排行榜类型">
          <el-select v-model="queryParams.rankingType" placeholder="请选择排行榜类型" style="width: 150px">
            <el-option label="总排行榜" value="total" />
            <el-option label="周排行榜" value="weekly" />
            <el-option label="月排行榜" value="monthly" />
            <el-option label="年排行榜" value="yearly" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-select v-model="queryParams.timeRange" placeholder="请选择时间范围" style="width: 150px">
            <el-option label="全部时间" value="all" />
            <el-option label="最近一周" value="week" />
            <el-option label="最近一月" value="month" />
            <el-option label="最近一年" value="year" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getRankingList">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 排行榜列表 -->
    <el-card class="ranking-list">
      <el-table
        v-loading="loading"
        :data="rankingList"
        style="width: 100%"
        :row-class-name="getRowClassName"
      >
        <el-table-column label="排名" align="center" width="80">
          <template slot-scope="scope">
            <div class="rank-number" :class="getRankClass(scope.$index)">
              {{ scope.row.rank }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="用户信息" align="left" min-width="200">
          <template slot-scope="scope">
            <div class="user-info">
              <div class="username">{{ scope.row.username }}</div>
              <div class="user-id">ID: {{ scope.row.userId }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="总分" align="center" width="100">
          <template slot-scope="scope">
            <span class="score">{{ scope.row.score }}</span>
          </template>
        </el-table-column>
        <el-table-column label="已解决题目" align="center" width="120">
          <template slot-scope="scope">
            <span class="solved-count">{{ scope.row.solvedProblems }}</span>
          </template>
        </el-table-column>
        <el-table-column label="提交次数" align="center" width="100">
          <template slot-scope="scope">
            {{ scope.row.totalSubmissions }}
          </template>
        </el-table-column>
        <el-table-column label="通过率" align="center" width="100">
          <template slot-scope="scope">
            <el-progress 
              :percentage="scope.row.acceptanceRate" 
              :color="getAcceptanceRateColor(scope.row.acceptanceRate)"
              :stroke-width="8"
            />
          </template>
        </el-table-column>
        <el-table-column label="平均执行时间" align="center" width="120">
          <template slot-scope="scope">
            {{ scope.row.avgExecutionTime }}ms
          </template>
        </el-table-column>
        <el-table-column label="最近活跃" align="center" width="180">
          <template slot-scope="scope">
            {{ parseTime(scope.row.lastActiveTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="viewUserProfile(scope.row)"
            >查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getRankingList"
      />
    </el-card>

    <!-- 用户详情对话框 -->
    <el-dialog title="用户详情" :visible.sync="userDetailVisible" width="800px">
      <el-descriptions :column="2" border v-if="selectedUser">
        <el-descriptions-item label="用户ID">{{ selectedUser.userId }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ selectedUser.username }}</el-descriptions-item>
        <el-descriptions-item label="排名">{{ selectedUser.rank }}</el-descriptions-item>
        <el-descriptions-item label="总分">{{ selectedUser.score }}</el-descriptions-item>
        <el-descriptions-item label="已解决题目">{{ selectedUser.solvedProblems }}</el-descriptions-item>
        <el-descriptions-item label="提交次数">{{ selectedUser.totalSubmissions }}</el-descriptions-item>
        <el-descriptions-item label="通过率">{{ selectedUser.acceptanceRate }}%</el-descriptions-item>
        <el-descriptions-item label="平均执行时间">{{ selectedUser.avgExecutionTime }}ms</el-descriptions-item>
      </el-descriptions>
      
      <el-divider content-position="left">最近提交记录</el-divider>
      <el-table :data="userSubmissions" style="width: 100%">
        <el-table-column label="题目" prop="problemName" />
        <el-table-column label="状态" prop="status">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="得分" prop="score" />
        <el-table-column label="提交时间" prop="submissionTime">
          <template slot-scope="scope">
            {{ parseTime(scope.row.submissionTime) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { getOjRanking } from "@/api/system/oj-practice";

export default {
  name: "OjRanking",
  components: {
    Pagination: () => import("@/components/Pagination")
  },
  data() {
    return {
      loading: false,
      total: 0,
      rankingList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        rankingType: "total",
        timeRange: "all"
      },
      userDetailVisible: false,
      selectedUser: null,
      userSubmissions: []
    };
  },
  created() {
    this.getRankingList();
  },
  methods: {
    /** 获取排行榜数据 */
    getRankingList() {
      this.loading = true;
      getOjRanking(this.queryParams.rankingType, this.queryParams.timeRange, this.queryParams.pageSize).then(response => {
        this.rankingList = response.data;
        this.total = response.data.length;
        this.loading = false;
      });
    },
    /** 重置查询条件 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        rankingType: "total",
        timeRange: "all"
      };
      this.getRankingList();
    },
    /** 获取行样式 */
    getRowClassName({ row, rowIndex }) {
      if (rowIndex < 3) {
        return 'top-rank';
      }
      return '';
    },
    /** 获取排名样式 */
    getRankClass(index) {
      if (index === 0) return 'rank-gold';
      if (index === 1) return 'rank-silver';
      if (index === 2) return 'rank-bronze';
      return 'rank-normal';
    },
    /** 获取通过率颜色 */
    getAcceptanceRateColor(rate) {
      if (rate >= 80) return '#67C23A';
      if (rate >= 60) return '#E6A23C';
      if (rate >= 40) return '#F56C6C';
      return '#909399';
    },
    /** 获取状态类型 */
    getStatusType(status) {
      const typeMap = {
        '已完成': 'success',
        '编译错误': 'danger',
        '运行时错误': 'danger',
        '时间超限': 'warning',
        '内存超限': 'warning'
      };
      return typeMap[status] || 'info';
    },
    /** 查看用户详情 */
    viewUserProfile(user) {
      this.selectedUser = user;
      this.userSubmissions = [
        {
          problemName: '两数之和',
          status: '已完成',
          score: 10,
          submissionTime: new Date()
        },
        {
          problemName: '最长回文子串',
          status: '已完成',
          score: 15,
          submissionTime: new Date()
        }
      ];
      this.userDetailVisible = true;
    },
    /** 时间格式化 */
    parseTime(time, cFormat) {
      if (arguments.length === 0 || !time) {
        return null;
      }
      const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
      let date;
      if (typeof time === 'object') {
        date = time;
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time);
        } else if (typeof time === 'string') {
          time = time.replace(new RegExp(/-/gm), '/');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000;
        }
        date = new Date(time);
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key];
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value]; }
        return value.toString().padStart(2, '0');
      });
      return time_str;
    }
  }
};
</script>

<style scoped>
.ranking-header {
  margin-bottom: 20px;
}

.header-content h2 {
  margin: 0;
  color: #303133;
}

.header-content p {
  margin: 10px 0 0 0;
  color: #909399;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  margin: 0;
}

.ranking-list {
  margin-bottom: 20px;
}

.rank-number {
  font-size: 18px;
  font-weight: bold;
  padding: 5px 10px;
  border-radius: 4px;
}

.rank-gold {
  background-color: #FFD700;
  color: #fff;
}

.rank-silver {
  background-color: #C0C0C0;
  color: #fff;
}

.rank-bronze {
  background-color: #CD7F32;
  color: #fff;
}

.rank-normal {
  background-color: #f5f7fa;
  color: #606266;
}

.user-info {
  text-align: left;
}

.username {
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.user-id {
  font-size: 12px;
  color: #909399;
}

.score {
  font-weight: bold;
  color: #67C23A;
  font-size: 16px;
}

.solved-count {
  font-weight: bold;
  color: #409EFF;
  font-size: 16px;
}

.top-rank {
  background-color: #f0f9ff;
}

.el-divider {
  margin: 20px 0;
}
</style> 